<?php 
class Ucenter extends BZ_Controller
{
    public function _init()
    {
        $this->load->helper(['common', 'email']);
        $this->load->model('user_model', 'user');
        $this->load->model('tourism_provider_model', 'tourism_provider');
        $this->load->model('user_related_self_model', 'user_related_self');
        $this->load->model('user_feedback_model', 'user_feedback');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('help_issue_model', 'help_issue');
    }

    public function index()
    {
        if ($this->uid && $this->validateUserType(UTID_PROVIDER)) {
            $this->redirect($this->config->gongying_url);
        }
        if ($this->uid) {
            $this->data['userInfo'] = $this->user->findUserInfo($this->uid)->row();
            $this->data['orderNum'] = $this->tourism_order->orderStatusTotal(['payer_uid' => $this->uid], true);
        }
        $this->data['orderStatus'] = ['2' => '待付款', '3' => '待发货', '4' => '待收货', '5' => '待评价'];
        $this->data['iconStatus']  = ['2' => 'icon-daifukuan', '3' => 'icon-31daifahuo', '4' => 'icon-31daishouhuo', '5' => 'icon-31daipingjia'];
        //dump($this->data['orderNum']);exit;
        $this->load->view('home/ucenter/index', $this->data);
    }

    /**
     * 个人信息
     */
    public function baseInfoSet()
    {
        $this->_checkLogin();
        $this->data['userInfo'] = $this->user->findUserInfo($this->uid)->row();
        $this->load->view('home/ucenter/baseInfoSet', $this->data);
    }

    /**
     * 修改呢称
     */
    public function modifyAlias()
    {
        $this->_checkLogin();
        $this->data['userInfo'] = $this->user->findOne(['uid' => $this->uid])->row();
        $this->load->view('home/ucenter/modifyAlias', $this->data);
    }

    public function modifyUserName()
    {
        $this->_checkLogin();
        $this->data['userInfo'] = $this->user->findOne(['uid' => $this->uid])->row();
        $this->load->view('home/ucenter/modifyUserName', $this->data);
    }

    /**
     * 修改呢称
     */
    public function modifyUserPost()
    {
        $this->_checkLogin();
        $alias    = $this->input->post('alias');
        $userName = $this->input->post('user_name');
        $data     = [];
        if ($alias) {
            if (strlen($alias) < 2 || strlen($alias) > 20) {
                $this->ajaxJson(false, '请输入呢称,呢称字数为2到20位');
            }
            $data['alias_name'] = $alias;
        }
        if ($userName) {
            if (checkMobile($userName)) {
                $this->ajaxJson(false, '用户名称不可以是手机号码~');
            }
            if (valid_email($userName)) {
                $this->ajaxJson(false, '用户名称不可以是邮箱地址~');
            }
            $res = $this->user->findOne(['user_name' => $userName, 'user_name !=' => $this->userName]);
            if ($res->num_rows() > 0) {
                $this->ajaxJson(false, '用户名称已经存在~');
            }
            $data['user_name'] = $userName;
        }
        $personalPhoto = $this->input->post('personal_photo');
        if (!empty($personalPhoto)) {
            $data['personal_photo'] = $personalPhoto;
        }
        $alias = $this->input->post('alias_name');
        if ($alias) {
            $data['alias_name'] = $alias;
        }
        $contacter = $this->input->post('contacter');
        if ($contacter) {
            $data['contacter'] = $contacter;
        }
        $sexId = $this->input->post('sex_id');
        if (in_array($sexId, [1, 2])) {
            $data['sex_id'] = $sexId;
        }
        if (empty($data)) {
            $this->ajaxJson(false, '填写信息不能为空~~');
        }

        $isUpdate = $this->user->update($data, ['uid' => $this->uid]);
        if (!$isUpdate) {
            $this->ajaxJson(['status' => false, 'msg' => '网络错误，请稍后重试~']);
        }
        $this->ajaxJson(['status' => true, 'msg' => '修改成功']);
    }

    /**
     * 二维码
     */
    public function qrCode()
    {
        $this->_checkLogin();
        $data = array(
            'url'                  => site_url(). '?username='. $this->userName, //二维码内容
            'errorCorrectionLevel' => 'L', //容错级别
            'matrixPointSize'      => 6, //生成图片大小
            'QR'                   => $this->config->upload_image_path($this->uid.'.png', 'qrcode/ewm'),
            'logo'                 => $this->config->upload_image_path('logo_30.png', 'skins/common/images'), //准备好的logo图片
            'output'               => $this->config->upload_image_path($this->uid.'.png', 'qrcode/ewm'),
        );
        $this->load->library('qrcode/qr_code', null, 'qr_code');
        $this->qr_code->generate($data);
        $this->load->view('home/ucenter/qrCode', $data);
    }
    
    public function helpCenter()
    {
        $res = $this->tourism_provider->findOne(['uid' => $this->providerUid]);
        if ($res->num_rows() <= 0) {
            show_404();
        }
        $this->data['service']    = $res->row(0);
        $this->data['help_issue'] = $this->help_issue->findByParams(['provider_id' => $this->providerUid, 'status' => 1], '*', null, 'sort ASC');

        $this->load->view('home/ucenter/helpCenter', $this->data);
    }

    /**
     * 用户是否登录
     */
    private function _checkLogin()
    {
        if (!$this->frontUser) {
             $this->redirect(site_url('login/login/index'));
        }
    }

    /**
     * 删除过期的文件,二维码
     */
    private function _deleteExpiredfiles($file_path)
    {
        $current_dir = @opendir($file_path);
        while ($filename = @readdir($current_dir)) {
            if (substr($filename, -4) === '.png' && (str_replace('.jpg', '', $filename) + $expiration) < $now) {
                @unlink($file_path.$filename);
            }
        }
        @closedir($current_dir);
    }
    
    /**
     *  账户切换
     */
    public function userSwitch()
    {
        $this->_checkLogin();
        $loginUser = array(
            'uid'           => $this->uid,
            'userType'      => $this->userType, 
            'userName'      => $this->userName, 
            'aliasName'     => $this->aliasName,
            'userTypeEn'    => $this->userTypeEn,
            'userTypeName'  => $this->userTypeName,
            'userParentId'  => $this->userParentId,
            'personalPhoto' => $this->personalPhoto,
            'extra'         => 0,
        );
        $data['userRelated'] = $this->getUserRelated();
        array_unshift($data['userRelated'], $loginUser); //讲数组数据插入到数组之前
        $this->load->view('home/ucenter/userSwitch', $data);
    }
    
    public function getUserRelated()
    {
        $userRelated = array();
        if ($this->userType&UTID_PROVIDER) {
            $result = $this->user_related_self->providerFxReult($this->uid);
        } else {
            $result = $this->user_related_self->resellerFxReult($this->uid);
        }
        if ($result->num_rows() <= 0) {
            return $userRelated;
        }
        //获取关联用户Uid
        $uids = array();
        foreach ($result->result() as $item) {
            if ($this->userType&UTID_PROVIDER) {
                $uids['uid'][] = $item->reseller_uid;
            } else {
                $uids['uid'][] = $item->provider_uid;
            }
        }
        if (empty($uids)) {
            return $userRelated;
        }
        //获取关联数据用户信息
        $result1 = $this->user->findByIds($uids);
        if ($result1->num_rows() <= 0) {
            return $userRelated;
        }
        foreach ($result1->result() as $user) {
            $userInfo = $this->usertype($user->user_type);
            $userRelated[] = array(
                'uid'           => $user->uid,
                'userType'      => $user->user_type,
                'userName'      => $user->user_name,
                'aliasName'     => $user->alias_name,
                'userTypeEn'    => $userInfo['type_en'],
                'userTypeName'  => $userInfo['type_zh'],
                'userParentId'  => $user->parent_id,
                'personalPhoto' => $user->personal_photo,
                'extra'         => $user->extra,
            );
        }
        return $userRelated;
    }

    public function feedback()
    {
        $this->load->view('home/ucenter/feedback', $this->data);
    }

    public function feedbackTo()
    {
        $type       = $this->input->post('type') ? $this->input->post('type') : 0;
        $content    = $this->input->post('content');
        $uploads    = $this->input->post('uploads') ? $this->input->post('uploads') : '';
        $emailPhone = $this->input->post('emailPhone');
        $mobile     = '';
        $email      = '';
        $providerId = (int)$this->config->store_id;
        if (!$providerId) {
            $this->ajaxJson(['status' => falinputse, 'msg' => '当前地址不合法~']);
        }
        if ($type <= 0) {
            $this->ajaxJson(['status' => false, 'msg' => '请选择反馈类型']);
        }
        if (empty($content)) {
            $this->ajaxJson(['status' => false, 'msg' => '反馈内容不能为空']);
        }
        if (strlen($content) < 2 || strlen($content) > 300) {
            $this->ajaxJson(['status' => false, 'msg' => '反馈内容须在2-300个字之间']);
        }
        /*
        if (empty($uploads)) {
            $this->ajaxJson(['status' => 0, 'msg' => '图片不能为空']);
        }
        */
        if (substr_count($uploads, '|') > 3) {
            $this->ajaxJson(['status' => false, 'msg' => '图片最多只能上传4张']);
        }
        if (valid_email($emailPhone)) {
            $email = $emailPhone;
        }
        if (!valid_mobile($emailPhone)) {
            $mobile = $emailPhone;
        }
        $data = [
            'uid'             => $this->uid ? $this->uid : 0,
            'provider_id'     => $providerId,
            'type'            => $type,
            'mobile'          => $mobile,
            'email'           => $email,
            'content'         => $content,
            'uploads'         => $uploads,
            'status'          => 0,
            'update_time'     => date('Y-m-d H:i:s'),
            'create_time'     => date('Y-m-d H:i:s'),
        ];
        $lastId = $this->user_feedback->insert($data, false, true);
        if (!$lastId) {
            $this->ajaxJson(['status' => false, 'msg' => '内部错误']);
        }
        $this->ajaxJson(['status' => true, 'msg' => '', 'data' => ['last_id' => $lastId, 'url' => site_url('home/ucenter/feedbackRes')]]);
    }

    public function feedbackRes()
    {
        $this->load->view('home/ucenter/feedbackRes', $this->data);
    }
}